#include "saveimagedialog.h"
#include "logger.h"

using namespace views;
using namespace utilities;

SaveImageDialog::SaveImageDialog(QWidget* parent) : QDialog(parent)
{
    _imageWidget = new ImageWidget(NULL);
    initUI();
    setupUI();
}

SaveImageDialog::SaveImageDialog(QWidget* parent, QImage& image) : QDialog(parent)
{
    _imageWidget = new ImageWidget(NULL, image.size());
    setImage(image);
    initUI();
    setupUI();
}

SaveImageDialog::~SaveImageDialog()
{
    delete _image;
    delete _btnSave;
    delete _btnCancel;
    delete _imageWidget;
}

void SaveImageDialog::initUI()
{
    _btnSave        = new QPushButton(QString::fromUtf8("Sauvegarder"));
    _btnCancel      = new QPushButton(QString::fromUtf8("Annuler"));

    connect(_btnSave, SIGNAL(clicked()), (SaveImageDialog*)this, SLOT(saveImage()));
    connect(_btnCancel, SIGNAL(clicked()), (SaveImageDialog*)this, SLOT(cancelSave()));

    this->setMinimumWidth(400);
    this->setMinimumHeight(300);
}

void SaveImageDialog::setupUI()
{
    // Main layout
    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(_imageWidget);

    // Add spacer
    QFrame* line = new QFrame();
    line->setFrameShape(QFrame::HLine);
    line->setFrameShadow(QFrame::Sunken);
    mainLayout->addWidget(line);

    // Lay out buttons
    QHBoxLayout *layout = new QHBoxLayout;
    layout->setSpacing(0);
    layout->addWidget(_btnSave, 0, Qt::AlignRight);
    layout->addWidget(_btnCancel, 0, Qt::AlignRight);
    mainLayout->addItem(layout);

    // Set the main layout
    this->setLayout(mainLayout);
    this->adjustSize();
}

void SaveImageDialog::setImage(QImage& image)
{
    _image = &image;
    _imageWidget->setImage(*_image);
}

void SaveImageDialog::saveImage()
{
    Logger::logMessage("SaveImageDialog::saveImage()");

    // Get the destination filename
    QString filename = QFileDialog::getSaveFileName(this, tr("Save Image"),
                                                    "../Recyk/Data/imgDB/", tr("Image Files (*.png *.jpg *.bmp)"));

    // Save image as PNG
    QImageWriter writer(filename, "png");
    writer.setText("Author", "Adama D. Zongo");
    writer.write(*_image);
    this->close();
}

void SaveImageDialog::cancelSave()
{
    Logger::logMessage("SaveImageDialog::cancelSave()");
    this->close();
}
